package com.yuke.cloud.service.pmc.service.impl;

import com.yuke.cloud.common.base.enums.ErrorCodeEnum;
import com.yuke.cloud.common.core.support.BaseService;
import com.yuke.cloud.common.core.utils.RequestUtil;
import com.yuke.cloud.common.util.RedisKeyUtil;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.cmc.dto.CmsSecKillDto;
import com.yuke.cloud.service.api.cmc.dto.CmsSecKillSkuDto;
import com.yuke.cloud.service.api.pmc.dto.*;
import com.yuke.cloud.service.api.pmc.dto.ProdAttributeDto;
import com.yuke.cloud.service.api.smc.dto.GoodsAndSpecInfoDto;
import com.yuke.cloud.service.api.smc.dto.ShopInfoDto;
import com.yuke.cloud.service.api.smc.exceptions.SmcBizException;
import com.yuke.cloud.service.api.smc.service.SmcFeignApi;
import com.yuke.cloud.service.api.wmc.dto.StorageDto;
import com.yuke.cloud.service.api.wmc.dto.StorageSpecInfoDto;
import com.yuke.cloud.service.api.wmc.dto.WareProductDto;
import com.yuke.cloud.service.api.wmc.exceptions.WmcBizException;
import com.yuke.cloud.service.api.wmc.service.WmcStorageFeignApi;
import com.yuke.cloud.service.pmc.dao.ProdSpecMapper;
import com.yuke.cloud.service.pmc.dto.*;
import com.yuke.cloud.service.pmc.entity.ProdCategory;
import com.yuke.cloud.service.pmc.entity.ProdSpec;
import com.yuke.cloud.service.pmc.entity.ProdSpecPicture;
import com.yuke.cloud.service.pmc.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * Created by zys on 2018/09/30.
 */
@Slf4j
@Service
@Transactional
public class ProdSpecServiceImpl extends BaseService<ProdSpec> implements ProdSpecService {
    @Resource
    private ProdSpecMapper prodSpecMapper;
    @Resource
    private ProdSpecPictureService prodSpecPictureService;
    @Resource
    private ProdProductService prodProductService;
    @Resource
    private ProdCategoryService prodCategoryService;
    @Resource
    private ProdSpecAttributeService prodSpecAttributeService;
    @Resource
    private SmcFeignApi smcFeignApi;
    @Resource
    private WmcStorageFeignApi wmcStorageFeignApi;

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private DicRegionService dicRegionService;

    @Override
    public int save(ProdSpec record) {
        record.setSpecId(generateId());
        //如果不支持退货，清空掉退货天数
        record.setCreateId(RequestUtil.getLoginUser().getUserId());
        if (record.getIsReturn() != null && !record.getIsReturn())
            record.setReturnPeriod(null);
        return super.save(record);
    }

    @Override
    public int update(ProdSpec entity) {
        //如果不支持退货，清空掉退货天数
        entity.setUpdateId(RequestUtil.getLoginUser().getUserId());
        if (entity.getIsReturn() != null && !entity.getIsReturn())
            entity.setReturnPeriod(null);
        int count = super.update(entity);
        return count;
    }

    @Override
    public int updateSpecStockPrice(ProdSpec entity) {
        return super.update(entity);
    }

    @Override
    public List<ProdSpecInfoAndPriceDto> getListRecommend(String longitude, String latitude) {
        List<ProdSpecInfoAndPriceDto> prodSpecInfoAndPriceDtos = prodSpecMapper.getRecommendAllList();
        if (prodSpecInfoAndPriceDtos.size() == 0) {
            return null;
        }

        return prodSpecInfoAndPriceDtos.stream().filter(prodSpecInfoAndPriceDto -> prodSpecInfoAndPriceDto.getSalePrice() != null).collect(Collectors.toList());
    }

    @Override
    public List<ProdSpecInfoDto> getSpecInfoBySpecIds(List<Long> specIds) {
        List<ProdSpecInfoDto> prodSpecInfoDtos = prodSpecMapper.getSpecInfoBySpecIds(specIds);

        return prodSpecInfoDtos;
    }

    @Override
    public List<ProdSpec> getEnableSpecByCategoryIds(List<Long> categoryIds) {
        return prodSpecMapper.getEnableSpecByCategoryIds(categoryIds);
    }

    @Override
    public List<ProdSpecByCategoryDto> getSpecByCategoryId(Long categoryId, Long shopId) {
        log.info("--- Enter getSpecByCategoryId(Long categoryId, Long shopId)，参数：{}, {} ---", categoryId, shopId);
        List<Long> leafCategoryIds = new ArrayList<>();
        prodCategoryService.leafCategoryId(categoryId, leafCategoryIds);
        if (leafCategoryIds.size() == 0) {
            log.info("--- Leave getSpecByCategoryId(Long categoryId, Long shopId), getProdByCategoryId(Long categoryId), {}分类是错误的，返回值：null ---", categoryId);
            return null;
        }
        //过滤掉未入库的商品（商品库存价格为0）
        List<ProdSpecByCategoryDto> prodSpecByShopIdDtos = prodSpecMapper.getSpecByCategoryIds(leafCategoryIds)
                .stream()
                .filter(prodSpecByCategoryDto -> prodSpecByCategoryDto.getStockPrice()!=0)
                .collect(Collectors.toList());
        if (prodSpecByShopIdDtos.size() == 0) {
            log.info("--- Leave getSpecByCategoryId(Long categoryId, Long shopId), leafCategoryIds={}分类下没有商品，返回值：null ---", leafCategoryIds);
            return null;
        }
        List<StorageDto> storageDtos = new ArrayList<>();
        List<GoodsAndSpecInfoDto> goodsAndSpecInfoDtoList = new ArrayList<>();
        prodSpecByShopIdDtos.forEach(prodSpecByCategoryDto -> {
                    StorageDto storageDto = new StorageDto();
                    storageDto.setShopId(shopId);
                    storageDto.setSpecId(prodSpecByCategoryDto.getSpecId());
                    storageDtos.add(storageDto);
                    GoodsAndSpecInfoDto goodsAndSpecInfoDto = new GoodsAndSpecInfoDto();
                    goodsAndSpecInfoDto.setShopId(shopId);
                    goodsAndSpecInfoDto.setSpecId(prodSpecByCategoryDto.getSpecId());
                    goodsAndSpecInfoDtoList.add(goodsAndSpecInfoDto);
                });
        List<StorageDto> storageDtoList = wmcStorageFeignApi.getStorageNum(storageDtos);
        if (storageDtoList == null || storageDtoList.size() == 0) {
            log.error("--- wmcStorageFeignApi.getStorageNum(storageDtos)内部异常，参数：{} ---", storageDtos);
            throw new WmcBizException(ErrorCodeEnum.GL99990002);
        }
        List<GoodsAndSpecInfoDto> goodsAndSpecInfoDtos = smcFeignApi.getGoodsStatusList(goodsAndSpecInfoDtoList);
        if (goodsAndSpecInfoDtos == null || goodsAndSpecInfoDtos.size() == 0) {
            log.error("--- smcFeignApi.getGoodsStatusList(goodsAndSpecInfoDtoList)内部异常，参数：{} ---", goodsAndSpecInfoDtoList);
            throw new SmcBizException(ErrorCodeEnum.GL99990002);
        }
        for (ProdSpecByCategoryDto prodSpecByCategoryDto:prodSpecByShopIdDtos) {
            for (GoodsAndSpecInfoDto goodsAndSpecInfoDto : goodsAndSpecInfoDtos) {
                if (goodsAndSpecInfoDto.getSpecId().equals(prodSpecByCategoryDto.getSpecId())) {
                    prodSpecByCategoryDto.setGoodsStatus(goodsAndSpecInfoDto.getGoodsStatus());
                }
                }
            for (StorageDto storageDto : storageDtoList) {
                if (storageDto.getSpecId().equals(prodSpecByCategoryDto.getSpecId())) {
                    prodSpecByCategoryDto.setStockCount(storageDto.getNumber());
                }
            }
        }
        log.info("--- Leave getSpecByCategoryId(Long categoryId, Long shopId)，返回值大小：{} ---", prodSpecByShopIdDtos.size());
        return prodSpecByShopIdDtos;
    }

    @Override
    public void deleteBySpecIds(String specIds) {
        List<Long> specIdList = Arrays.asList(specIds.split(",")).stream().map(id -> Long.valueOf(id)).collect(Collectors.toList());

        prodSpecAttributeService.deleteBySpecIds(specIds);

        List<ProdSpecPicture> prodSpecPictures = prodSpecPictureService.getProdSpecPicBySpecIds(specIdList);
        prodSpecPictureService.deleteBySpecIds(specIdList);

        List<Long> productIdList = prodSpecMapper.getProductIdsBySpecIds(specIdList);
        this.deleteByIds(specIds);

        for (Long productId : productIdList) {
            Example example = new Example(ProdSpec.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("productId", productId);
            int count = prodSpecMapper.selectCountByExample(example);
            if (count == 0) {
                prodProductService.deleteById(productId);
            }
        }

        prodSpecPictureService.deleteFromFastDFS(prodSpecPictures);
    }

    @Override
    public void isEnable(Long specId, Integer isEnable) {
        prodSpecMapper.isEnable(specId, isEnable);
        if (isEnable == 1) {
            //同时要确保所在分类启用
            prodCategoryService.isEnable(prodSpecMapper.getCategoryBySpecId(specId), 1);
        }
    }

    @Override
    public void isEnableProduct(Long productId, Long specId,Integer isEnable) {
        prodSpecMapper.isEnableProduct(productId, isEnable);
        if (isEnable == 1) {
            //同时要确保所在分类启用
            prodCategoryService.isEnable(prodSpecMapper.getCategoryBySpecId(specId), 1);
        }
    }

    @Override
    public List<ProdSpecInfoAndPriceDto> getAppSpecByCondition(ProdSpecInfoAndPriceDto prodSpecInfoAndPrice, Long shopId) {

        // add by wg 20190611 对排序方式进行判断
        if (prodSpecInfoAndPrice != null && prodSpecInfoAndPrice.getSortPriceType() != null) {
            String sortPriceType = prodSpecInfoAndPrice.getSortPriceType();
            if (!sortPriceType.equalsIgnoreCase("asc") && !sortPriceType.equalsIgnoreCase("desc")) {
                return new ArrayList<>();
            }
        }
        if (prodSpecInfoAndPrice != null && prodSpecInfoAndPrice.getSortCountType() != null) {
            String sorCountType = prodSpecInfoAndPrice.getSortCountType();
            if (!sorCountType.equalsIgnoreCase("asc") && !sorCountType.equalsIgnoreCase("desc")) {
                return new ArrayList<>();
            }
        }

        List<ProdSpecInfoAndPriceDto> prodSpecInfoAndPriceDtos = new ArrayList<>();
        prodSpecInfoAndPriceDtos = prodSpecMapper.getAppSpecByCondition(prodSpecInfoAndPrice);

        if (prodSpecInfoAndPriceDtos.size() == 0) {
            return prodSpecInfoAndPriceDtos;
        }

        getSpecInfoExtra(shopId, prodSpecInfoAndPriceDtos, prodSpecInfoAndPrice.getSaleType());
        //如果商家端不过滤
        if (prodSpecInfoAndPrice.getSaleType().toString().equals("2")){
            return prodSpecInfoAndPriceDtos;
        }else{
            //用户端过滤
            List<ProdSpecInfoAndPriceDto> p1=new ArrayList<>();
            if (prodSpecInfoAndPriceDtos!=null&&prodSpecInfoAndPriceDtos.size()>0) {
                 p1 = prodSpecInfoAndPriceDtos.stream().collect(
                        Collectors.collectingAndThen(
                                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(ProdSpecInfoAndPriceDto::getProductId))), ArrayList::new)
                );
                 //按创建时间排序
                p1.sort(Comparator.comparing(ProdSpecInfoAndPriceDto::getCreateTime).reversed());
            }
            if (prodSpecInfoAndPrice != null && prodSpecInfoAndPrice.getSortPriceType() != null) {
                String sortPriceType = prodSpecInfoAndPrice.getSortPriceType();
                if (!sortPriceType.equalsIgnoreCase("asc") ) {
                    p1.sort(Comparator.comparing(ProdSpecInfoAndPriceDto::getSalePrice));
                }else if (!sortPriceType.equalsIgnoreCase("desc")){
                    p1.sort(Comparator.comparing(ProdSpecInfoAndPriceDto::getSalePrice).reversed());
                }
            }
            if (prodSpecInfoAndPrice != null && prodSpecInfoAndPrice.getSortCountType() != null) {
                String sortCountType = prodSpecInfoAndPrice.getSortCountType();
                if (!sortCountType.equalsIgnoreCase("asc") ) {
                    p1.sort(Comparator.comparing(ProdSpecInfoAndPriceDto::getSaleCount));
                }else if (!sortCountType.equalsIgnoreCase("desc")){
                    p1.sort(Comparator.comparing(ProdSpecInfoAndPriceDto::getSaleCount).reversed());
                }
            }
            return p1;
        }


    }

    @Override
    public ProdSpecInfoDto getSpecInfoBySpecId(Long specId) {
        ProdSpecInfoDto prodSpecInfoDto = prodSpecMapper.getSpecInfoBySpecId(specId);
        return prodSpecInfoDto;
    }

    @Override
    public List<ProdSpecInfoDto> getSpecInfoDtosByCategoryId(Long categoryId) {
        List<Long> categoryIds = new ArrayList<>();
        prodCategoryService.leafCategoryId(categoryId, categoryIds);
        if (categoryIds.size()<=0) {
            return null;
        }
        List<ProdSpecInfoDto> prodSpecInfoDtos = prodSpecMapper.getSpecInfoDtosByCategoryIds(categoryIds);
        return prodSpecInfoDtos;
    }

    @Override
    public List<ProdSpecInfoDto> getSpecInfoDtosByCondition(ProdSpecInfoDto prodSpecInfoDto) {
        List<Long> categoryIds = new ArrayList<>();
        if (prodSpecInfoDto.getCategoryId() != null) {
            prodCategoryService.leafCategoryId(prodSpecInfoDto.getCategoryId(), categoryIds);
        }
        return prodSpecMapper.getSpecInfoDtosByCondition(prodSpecInfoDto, categoryIds);
    }

    @Override
    public Map<String, Integer> getPriceBySpecId(Long specId) {
        Map<String, Integer> prices = prodSpecMapper.getPriceBySpecId(specId);
        return prices;
    }

    @Override
    public List<ProdSpecInfoAndPriceDto> getSpecInfoDtosBySpecIds(List<Long> ids) {
        List<ProdSpecInfoAndPriceDto> prodSpecInfoAndPriceDtos = new ArrayList<>();
        if (ids != null && ids.size() > 0) {
            prodSpecInfoAndPriceDtos = prodSpecMapper.getSpecInfoDtosBySpecIds(ids);
        }
        if (prodSpecInfoAndPriceDtos.size() < 6) {
            prodSpecInfoAndPriceDtos.addAll(prodSpecMapper.getRecommendAllList());
        }

        return prodSpecInfoAndPriceDtos.subList(0,6);
    }

    @Override
    public List<ProdSpecInfoDto> getSpecInfoListBySpecIds(List<Long> specIds) {
        return prodSpecMapper.getSpecInfoListBySpecIds(specIds);
    }

    @Override
    public List<ProdSpecInfoDto> getSpecBySpecName(ProdSpecInfoDto prodSpecInfoDto) {
        return prodSpecMapper.getSpecBySpecName(prodSpecInfoDto);
    }

    @Override
    public List<ProdSpecInfoDto> getBySpecName(ProdSpecInfoDto prodSpecInfoDto) {
        return prodSpecMapper.getBySpecName(prodSpecInfoDto);
    }

    @Override
    public List<ProdBrandDto> getBrands(Long categoryId, Byte saleType, String keyWord) {
        return prodSpecMapper.getBrands(categoryId, saleType, keyWord);
    }

    @Override
    public void updateSpecSaleCount(List<ProdSpecInfoDto> prodSpecInfoDtos) {
        if (prodSpecInfoDtos != null && prodSpecInfoDtos.size() > 0) {
            for (ProdSpecInfoDto prodSpecInfoDto : prodSpecInfoDtos) {
                prodSpecMapper.updateSaleCount(prodSpecInfoDto.getSpecId(), prodSpecInfoDto.getSaleCount());
            }
        }
    }

    // 获取正在秒杀活动中的商品
    private List<SecKillSkuInfoDto> getSecKillSkus() {
        Set<String> keys = redisTemplate.keys(RedisKeyUtil.getSecKillKeys());

        if (CollectionUtils.isEmpty(keys)) {
            return new ArrayList<>();
        }

        List<SecKillSkuInfoDto> secKillSkuInfoDtoList = new ArrayList<>();
        Date now = new Date();
        for (String secKillKey : keys) {
            CmsSecKillDto cmsSecKillDto = (CmsSecKillDto)redisTemplate.opsForValue().get(secKillKey);
            if (cmsSecKillDto != null && cmsSecKillDto.getIsEnable() && now.getTime() >= cmsSecKillDto.getStartTime().getTime()
                    && now.getTime() <= cmsSecKillDto.getEndTime().getTime()) {
                Set<String> skuKeys = redisTemplate.keys(RedisKeyUtil.getSecKillSkuKeys(String.valueOf(cmsSecKillDto.getSecKillId())));

                for (String skuKey : skuKeys) {
                    CmsSecKillSkuDto cmsSecKillSkuDto = (CmsSecKillSkuDto)redisTemplate.opsForValue().get(skuKey);
                    SecKillSkuInfoDto secKillSkuInfoDto = new SecKillSkuInfoDto();
                    secKillSkuInfoDto.setCmsSecKillSkuDto(cmsSecKillSkuDto);
                    secKillSkuInfoDto.setSecKillEndTime(cmsSecKillDto.getEndTime());
                    if (cmsSecKillSkuDto != null) {
                        secKillSkuInfoDtoList.add(secKillSkuInfoDto);
                    }
                }
            }
        }

        return secKillSkuInfoDtoList;
    }

    @Override
    public List<ProdSpecInfoAndPriceDto> getSpecBySpecIds(Long shopId, List<Long> specIds, Byte saleType) {

        List<ProdSpecInfoAndPriceDto> prodSpecInfoAndPriceDtos = new ArrayList<>();
        prodSpecInfoAndPriceDtos = prodSpecMapper.getSpecBySpecIds(specIds, saleType);
        if (prodSpecInfoAndPriceDtos.size() == 0) {
            return prodSpecInfoAndPriceDtos;
        }

        getSpecInfoExtra(shopId, prodSpecInfoAndPriceDtos, saleType);
        System.out.println("zzzzzzzzzzzzzzzzz"+prodSpecInfoAndPriceDtos);
        return prodSpecInfoAndPriceDtos;
    }

    @Override
    public void getSpecInfoExtra(Long shopId, List<ProdSpecInfoAndPriceDto> prodSpecInfoAndPriceDtos, Byte saleType) {
        // 根据店铺获取所在城市的商品库存量
        List<Long> specIds = new ArrayList<>();
        // 需要从远程仓库获取信息的商品
        List<Long> remoteSpecIds = new ArrayList<>();
        prodSpecInfoAndPriceDtos.forEach(prodSpecInfoAndPriceDto -> {
            specIds.add(prodSpecInfoAndPriceDto.getSpecId());
            remoteSpecIds.add(prodSpecInfoAndPriceDto.getSpecId());
        });
        Long warehouseId = null;

        if (shopId != null) {
            // 获取店名
            List<Long> listShopIds = new ArrayList<>();
            listShopIds.add(shopId);
            System.out.println("PMC+++++++prodSpecserviceImpl=++++++++listShopIds="+listShopIds);
            //根据店铺id集合获取
           /* regionProvinceId店铺所在省份ID
            regionCityId店铺所在城市ID
            regionCountyId店铺所在区县ID*/
            List<ShopInfoDto> shopInfoDtoList = smcFeignApi.getShopInfoByShopIds(listShopIds);
            if (shopInfoDtoList != null && shopInfoDtoList.size() > 0) {

                if (specIds.size() > 0) {
                    // add by wg 20190716 获取商品仓库相关信息
                    //根据店铺id获取店铺所属仓库Id 若获取为空则默认为6
                    Wrapper wrapperRet = wmcStorageFeignApi.getwarehouseidbyshopid(shopId);
                    //判断结果集是否为空和对应的返回码
                    if (wrapperRet != null && wrapperRet.getCode() == 200 && wrapperRet.getResult() != null) {
                        //获取结果集转换为Long类型
                        warehouseId = Long.valueOf(wrapperRet.getResult().toString());
                    } else {
                        //若为空则返回微服务不在线
                        throw new SmcBizException(ErrorCodeEnum.GL99990002);
                    }
                    //根据店铺所在城市ID获取ProvinceAndCityInfoDto对象
                    ProvinceAndCityInfoDto provinceAndCityInfoDto = dicRegionService.getProvinceAndCityInfoByCityId(shopInfoDtoList.get(0).getRegionCityId());
                    //根据店铺所在城市ID和商品规格ID集合 获取规格id和库存
                    //Wrapper<Map<Long, Integer>> stockCount = wmcStorageFeignApi.getCityStockCount(shopInfoDtoList.get(0).getRegionCityId(), specIds);
                    List<StorageSpecInfoDto> storageSpecInfoDtoList = wmcStorageFeignApi.getWmsSpecInfoBySpecIds(specIds,shopId);
                    //判断结果集是否为空
                    if (storageSpecInfoDtoList != null && storageSpecInfoDtoList.size() > 0) {
                        //获取结果
                       for (StorageSpecInfoDto storageSpecInfoDto : storageSpecInfoDtoList) {

                           for (ProdSpecInfoAndPriceDto prodSpecInfoAndPriceDto : prodSpecInfoAndPriceDtos) {
                               if (storageSpecInfoDto.getSpecId().equals(prodSpecInfoAndPriceDto.getSpecId())){
                                   //todo 20191114 如果有秒杀商品，把秒杀商品的价格统一为商家端销售价
                                   //空不等于是否为秒杀活动商品
                                   if (null != prodSpecInfoAndPriceDto.getIsSecKill()) {
                                       //秒杀商品是否为true
                                       if (prodSpecInfoAndPriceDto.getIsSecKill()) {
                                           //将秒杀价格设置为B端商品价格
                                           prodSpecInfoAndPriceDto.setSecKillPrice(prodSpecInfoAndPriceDto.getSalePrice());
                                       }
                                   }
                                   //根据商品规格ID获取对应商品库存
                                   Integer stockCnt = storageSpecInfoDto.getStockCount();
                                   if (stockCnt == null || stockCnt <= 0) {
                                       stockCnt = 0;
                                   } else {
                                       // 移去有库存量的商品
                                       remoteSpecIds.remove(Long.valueOf(prodSpecInfoAndPriceDto.getSpecId()));
                                   }
                                   //设置库存量
                                   prodSpecInfoAndPriceDto.setStockCount(stockCnt);

                                   // add by wg 20190716 获取商品仓库相关信息
                                   if (stockCnt != null && stockCnt > 0) {
                                       //设置仓库Id
                                       prodSpecInfoAndPriceDto.setWarehouseId(warehouseId);
                                       //设置商品所在城市Id
                                       prodSpecInfoAndPriceDto.setWareCityId(shopInfoDtoList.get(0).getRegionCityId());
                                       if (provinceAndCityInfoDto != null) {
                                           //设置商品所在城市名称
                                           prodSpecInfoAndPriceDto.setWareCityName(provinceAndCityInfoDto.getProvinceName() + provinceAndCityInfoDto.getCityName());
                                       }
                                   }

                                   //设置价格
                                   prodSpecInfoAndPriceDto.setGuidancePrice(storageSpecInfoDto.getGuidancePrice());
                                   if (saleType.equals((byte)2)){
                                       prodSpecInfoAndPriceDto.setSalePrice(storageSpecInfoDto.getStockPrice());
                                   }else{
                                       prodSpecInfoAndPriceDto.setSalePrice(storageSpecInfoDto.getMarketPrice());
                                   }

                               }

                           }
                       }
                    }
                }
            }
        }

        // add by wg 20190605 判断秒杀商品
        // 店铺进货商品不获取秒杀价
        if (saleType != null && !saleType.equals((byte)2)) {
            System.out.println("saleType="+saleType);
            // add by wg 20190716 对远程仓库的货进行处理，如果前面获取到的货库存量为空或为0，则尝试从远程仓库获取
            if (shopId != null && remoteSpecIds.size() > 0 && warehouseId != null) {
                //根据商品规格Id集合和仓库ID获取WareProductDto对象
                Wrapper<List<WareProductDto>> listWrapper = wmcStorageFeignApi.getRemoteStock(remoteSpecIds, warehouseId);
                if (listWrapper != null && listWrapper.getCode() == 200) {
                    List<WareProductDto> listWareProductDto = listWrapper.getResult();
                    if (listWareProductDto != null && listWareProductDto.size() > 0) {
                        for (WareProductDto wareProductDto : listWareProductDto) {
                            for (ProdSpecInfoAndPriceDto prodSpecInfoAndPriceDto : prodSpecInfoAndPriceDtos) {
                                //判断商品规格是否相等
                                if (wareProductDto.getSpecId().longValue() == prodSpecInfoAndPriceDto.getSpecId().longValue()
                                        && wareProductDto.getStockCount() > 0) {
                                    prodSpecInfoAndPriceDto.setWarehouseId(wareProductDto.getWarehouseId());
                                    prodSpecInfoAndPriceDto.setWareCityId(wareProductDto.getCityId());
                                    prodSpecInfoAndPriceDto.setWareCityName(wareProductDto.getProvinceName() + wareProductDto.getCityName());
                                    prodSpecInfoAndPriceDto.setStockCount(wareProductDto.getStockCount());
                                }
                            }
                        }
                    }
                }
            }
            //获取正在秒杀活动中的商品
            List<SecKillSkuInfoDto> secKillSkuInfoDtos = getSecKillSkus();

            for (SecKillSkuInfoDto secKillSkuInfoDto : secKillSkuInfoDtos) {
                for (ProdSpecInfoAndPriceDto prodSpecInfoAndPriceDto : prodSpecInfoAndPriceDtos) {
                    //若秒杀活动商品规格Id等于商品规格id
                    if (secKillSkuInfoDto.getCmsSecKillSkuDto().getSpecId().longValue() == prodSpecInfoAndPriceDto.getSpecId().longValue()) {
                        //判断秒杀活动库存是否大于秒杀活动锁定库存
                        if ((secKillSkuInfoDto.getCmsSecKillSkuDto().getStoreCount() - secKillSkuInfoDto.getCmsSecKillSkuDto().getLockCount()) > 0) {
                            //则设置该商品为秒杀活动商品
                            prodSpecInfoAndPriceDto.setIsSecKill(true);
                            //todo 20191104  SecKillPrice 改为salePrice。//secKillSkuInfoDto.getCmsSecKillSkuDto().getSecKillPrice()
                            //设置秒杀价格
                            prodSpecInfoAndPriceDto.setSecKillPrice(prodSpecInfoAndPriceDto.getSalePrice());
                            //设置秒杀时间
                            prodSpecInfoAndPriceDto.setSecKillEndTime(secKillSkuInfoDto.getSecKillEndTime());
                        }
                    }
                }
            }
        }
    }

    @Override
    public List<ProdSpecGoodsDto> getProdSpecGoods(ProdSpecGoodsDto prodSpecGoodsDto) {

        List<ProdSpecGoodsDto> prodSpecGoods = prodSpecMapper.getProdSpecGoods(prodSpecGoodsDto);
        //todo 从wmcstorage拿到价格
        if (prodSpecGoods == null || prodSpecGoods.size()<1){
            return prodSpecGoods ;
        }
        List<Long> specIds = prodSpecGoods.stream().map(ProdSpecGoodsDto::getSpecId).collect(Collectors.toList());
        List<StorageSpecInfoDto> storageSpecInfoDtoList =wmcStorageFeignApi.getWmsSpecInfoBySpecIds(specIds,prodSpecGoodsDto.getShopId());
        if (storageSpecInfoDtoList != null && storageSpecInfoDtoList.size()>0){
            for(ProdSpecGoodsDto item : prodSpecGoods ){
                for(StorageSpecInfoDto spec : storageSpecInfoDtoList){
                    if (item.getSpecId().equals(spec.getSpecId())){
                        item.setGoodsPrice(spec.getStockPrice());
                        item.setMarketPrice(spec.getMarketPrice());
                        item.setStockPrice(spec.getStockPrice());
                        if (spec.getNumber()-spec.getLockNumber() >= 0){
                            item.setStockCount(spec.getNumber()-spec.getLockNumber());
                        }else{
                            item.setStockCount(0);
                        }

                    }

                }

            }
        }
        return prodSpecGoods ;
    }

    @Override
    public List<ProdMainAttrDetailDto> getMainAttribute(Long specId) {
        ProdSpec prodSpec = super.findById(specId);

        if (prodSpec != null) {
            return prodSpecMapper.getMainAttribute(specId, prodSpec.getProductId());
        }

        return null;
    }

    @Override
    public ProdMainAttrDto getMainAttributeList(Long specId, Byte saleType) {

        ProdSpec prodSpec = super.findById(specId);
        if (prodSpec != null) {
            ProdMainAttrDto prodMainAttrDto = new ProdMainAttrDto();
            prodMainAttrDto.setProductId(prodSpec.getProductId());

            List<ProdMainAttrDetailDto> list = prodSpecMapper.getMainAttributeList(prodSpec.getProductId(), saleType);
            prodMainAttrDto.setMainAttrList(list);

            return prodMainAttrDto;
        }

        return null;
    }

    @Override
    public ProdSpecInfoAndPriceDto getSpecByMainAttribute(ProdMainAttrDto prodMainAttrDto, Byte saleType, Long shopId) {
        List<ProdSpecInfoAndPriceDto> list = prodSpecMapper.getSpecByMainAttribute(prodMainAttrDto, saleType);

        if (list != null && list.size() > 0) {
            List<ProdSpecInfoAndPriceDto> listRet = new ArrayList<>();
            listRet.add(list.get(0));
            getSpecInfoExtra(shopId, listRet, saleType);
            System.out.println("----getSpecByMainAttribute---结果："+listRet.get(0));
            return listRet.get(0);
        }

        return null;
    }

    @Override
    public List<ProdSpecInfoExDto> getSpecIds(ProdStorageDto prodStorageDto) {

        List<ProdSpecInfoExDto> specIds = prodSpecMapper.getSpecIds(prodStorageDto);

        return specIds;
    }

    @Override
    public List<ProdSpecInfoDto> getImportSpecId(String specName) {
        List<ProdSpecInfoDto> importSpecId = prodSpecMapper.getImportSpecId(specName);
        return importSpecId;
    }

    @Override
    public List<ProdSpecGoodsInfoDto> findSpecAll(Long groupId){
        List<ProdSpecGoodsInfoDto> specList = prodSpecMapper.findSpecAll();

        return specList;
    }

    @Override
    public List<ProdAttributeDto> getFindProdAttributes(List<Long> specIds) {
        List<ProdAttributeDto> findProdAttributes = prodSpecMapper.getFindProdAttributes(specIds);
        return findProdAttributes;
    }

    @Override
    public int updateSpecCode(ProdSpec entity) {


        return prodSpecMapper.updateSpecCode(entity);
    }

    @Override
    public Boolean addProducRecording(String userId, String specId) {
        String key = "User:" + userId + ":Recording";

        //获取当前时间用来排序
        long time= System.currentTimeMillis();
        Boolean add = redisTemplate.opsForZSet().add(key, specId, (double)time);

        //保存超过100个则弹出最先浏览单商品ID
        Long size = redisTemplate.opsForZSet().size(key);
        if (size > 100) redisTemplate.opsForZSet().removeRange(key, 0, size-101);

        return add;
    }

    @Override
    public List<StorageSpecInfoDto> getRecordingByUserId(String userId,String shopId) {

        //取用户浏览商品id
        String key = "User:" + userId + ":Recording";
        Set<Long> specIds = redisTemplate.opsForZSet().range(key, 0, -1);

        List<StorageSpecInfoDto> storageSpecInfoDtoList= new ArrayList<>();

        if (specIds != null && specIds.size() > 0){
            List<Long> prodSpecIds = new ArrayList<>(specIds);
            storageSpecInfoDtoList = wmcStorageFeignApi.getStorageInfoBySpecIds(prodSpecIds,Long.parseLong(shopId));
        }

        return storageSpecInfoDtoList;
    }

    @Override
    public List<ProdSpecInfoDto> getStorageSpecInfoBySpecIds(List<Long> specIds){
        List<ProdSpecInfoDto> qq = prodSpecMapper.getStorageSpecInfoBySpecIds(specIds);
       return qq;
    }

    @Override
    public List<ProdSpecInfoDto> getSpecIdByCategoryId(ProdCategoryDto prodCategoryDto) {
        List<Long> list = new ArrayList<>();
        if (prodCategoryDto.getParentId()!=null&&!prodCategoryDto.getParentId().equals(0L)){
            //找出子节点
            Example example = new Example(ProdCategory.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("parentId",prodCategoryDto.getParentId());
            List<ProdCategory> prodCategories = prodCategoryService.selectByExample(example);
            List<Long> categoryList = prodCategories.stream().map(ProdCategory::getCategoryId).collect(Collectors.toList());
            list.addAll(categoryList);
            System.out.println(list);
        }else{
            list.add(prodCategoryDto.getCategoryId());
        }
        List<ProdSpecInfoDto> specList = prodSpecMapper.getSpecIdByCategoryId(list);

        return specList;
    }

    @Override
    public List<ProdSpecApiDto> getSpecNameBySpecIds(List<Long> list) {
        List<ProdSpecApiDto> prodSpecApiDtoList = prodSpecMapper.getSpecNameBySpecIds(list);
        return prodSpecApiDtoList;
    }

    @Override
    public List<ProdSpecGoodsInfoDto> getSpecInfoBySpecCode(String specCode){
        List<ProdSpecGoodsInfoDto> prodSpecApiDtoList = prodSpecMapper.getSpecInfoBySpecCode(specCode);
        return prodSpecApiDtoList;
    }

    @Override
    public List<ProdSpecApiDto> checkSpeCode(List<String> specCode) {
        return prodSpecMapper.checkSpeCode(specCode);
    }


}
